package com.hzw.saas.common.storage.rsync;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import lombok.extern.slf4j.Slf4j;

/**
 * @author zzl
 * @since 06/24/2021
 */
@Slf4j
public final class RsyncIOUtil {



    /**
     * randomAccessFile 指定位置读取缓存
     */
    public static int readBuffer(RandomAccessFile raf, long pos, byte[] buffer) throws IOException {
        return readBuffer(raf, pos, buffer, 0, buffer.length);
    }

    /**
     * randomAccessFile 指定位置读取缓存
     *
     * @param raf    文件流
     * @param pos    读取起始位置
     * @param buffer 读取缓存
     * @param offset buffer 偏移量
     * @param length 读取长度
     * @return 实际读取的字节数，-1表示已至文件末尾，无更多数据
     * @throws IOException e
     */
    public static int readBuffer(RandomAccessFile raf, long pos, byte[] buffer, int offset, int length) throws IOException {
        if (offset < 0 || length < 0 || (offset + length) > buffer.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
        raf.seek(pos);
        int read = raf.read(buffer, offset, length);
        log.trace("RAF读取文件块，{offset: {}, length: {}}", pos, read);
        return read;
    }

    /**
     * InputStream 读取缓存
     */
    public static int readBuffer(InputStream ins, byte[] buffer) throws IOException {
        return readBuffer(ins, buffer, 0, buffer.length);
    }

    /**
     * InputStream 读取缓存
     *
     * @param ins    文件流
     * @param buffer 读取缓存
     * @param offset buffer 偏移量
     * @param length 读取长度
     * @return 实际读取的字节数，-1表示已至文件末尾，无更多数据
     * @throws IOException e
     */
    public static int readBuffer(InputStream ins, byte[] buffer, int offset, int length) throws IOException {
        if (offset < 0 || length < 0 || (offset + length) > buffer.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
        int read = ins.read(buffer, offset, length);
        log.trace("INS读取文件块，{length: {}}", read);
        return read;
    }


    /**
     * inputStream 读取滚动缓存
     * 读取length长度的字节数填充至buffer的末尾，buffer中原先的字节依次向左移动length位
     * <p>
     * 备用，该方法有缓存问题未解决
     *
     * @param ins    文件流
     * @param buffer 读取缓存
     * @param length 文件流要读取的长度
     * @return 实际读取的字节数，-1表示已至文件末尾，无更多数据
     * @throws IOException e
     */
    private static int readRollingBuffer(InputStream ins, byte[] buffer, int length) throws IOException {
        // FIXME: ZZL@06/22/2021 文件末尾的缓存问题
        System.arraycopy(buffer, length, buffer, 0, buffer.length - length);
        int read = ins.read(buffer, buffer.length - length, length);
        log.trace("INS读取滚动文件块, {stepLength: {}, length: {}}", length, read);
        return read;
    }

    /**
     * Suppresses default constructor.
     */
    private RsyncIOUtil() {
        throw new UnsupportedOperationException("Private constructor, cannot be accessed.");
    }
}
